package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.NewsAuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
//import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl  extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 查询文章
     * @param dto
     * @return
     */
    //1.检查参数        //分页参数检查    //获取当前登录人的信息        //2.分页条件查询 //状态精确查询        //频道精确查询        //时间范围查询

    //关键字模糊查询//查询当前登录用户的文章  //发布时间倒序查询     分页查询

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        if (dto==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        WmUser user = WmThreadLocalUtil.getUser();
        if (user==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        IPage iPage=new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper=new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getChannelId()!=null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if (dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null){
            wrapper.between(WmNews::getCreatedTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        if (dto.getKeyword()!=null){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        wrapper.eq(WmNews::getUserId,WmThreadLocalUtil.getUser().getId());

        wrapper.orderByDesc(WmNews::getCreatedTime);

        page(iPage,wrapper);

        ResponseResult responseResult=new PageResponseResult(dto.getPage(),dto.getSize(),(int)iPage.getTotal());

        responseResult.setData(iPage.getRecords());

        return responseResult;

    }
//0.条件判断 //1.保存或修改文章//属性拷贝 属性名词和类型相同才能拷贝 //封面图片  list---> string

    //如果当前封面类型为自动 -1 //2.判断是否为草稿  如果为草稿结束当前方法

    /**
     * 文章发布
     * @param dto
     * @return
     */

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Autowired
    private WmNewsTaskService  wmNewsTaskService;
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //参数判断
        if (dto==null||dto.getContent()==null){
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存或修改文章
                    WmNews wmNews = new WmNews();
                    BeanUtils.copyProperties(dto,wmNews);
        //使用StringUtils.join把URL路径集合通过","拼接成一个字符串
        if (dto.getImages()!=null&&dto.getImages().size()>0){
            String joinImage = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(joinImage);
        }

        //无类型
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        //保存或修改文章方法
        saveOrUpdateWmNews(wmNews);
        //如果为草稿结束当前方法
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //不是草稿，才保存文章内容图片与素材的关系
        //提取文章内容中的图片信息
        List<String> imagesLists = imagesList(dto.getContent());
        //
        saveRelativeInfoForContent(imagesLists,wmNews.getId());
        //如果封面为自动，获取文章内容中的做为封面，
        //根据图片的数量自动转换type0 无图文章 1 单图文章 3 多图文章
        saveRelativeInfoForCover(dto, wmNews,imagesLists);

        //审核文章
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        //添加延迟任务
        wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补重文章数据
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //默认上架
        wmNews.setEnable((short)1);
        if (wmNews.getId()==null){
        //无id就是新增文章
            save(wmNews);
        }else {
            //有id就是新增文章//删除图文关系重新设置
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }
    }

    private void saveRelativeInfoForContent(List<String> imagesLists, Integer id) {
        saveRelativeInfo(imagesLists,id,WemediaConstants.WM_CONTENT_REFERENCE);
    }

    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews,List<String> imagesLists) {
        List<String> imagesList= dto.getImages();
//        第一个功能：如果当前封面类型为自动，则设置封面类型的数据
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
                if (imagesLists.size()>=3){
                    imagesList=imagesLists.stream().limit(3).collect(Collectors.toList());
                    wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                }else if (imagesLists.size()>=1&&imagesLists.size()<3){
                    imagesList=imagesLists.stream().limit(1).collect(Collectors.toList());
                    wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                }else{
                    wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                }

            //修改文章
            if( imagesList!= null && imagesList.size() > 0){
                wmNews.setImages(StringUtils.join(imagesList,","));
            }
                 updateById(wmNews);
//
        }
        //           第二个功能：保存封面图片与素材的关系
            if( imagesList!= null && imagesList.size() > 0){
                saveRelativeInfo(imagesList,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
            }
    }

    private void saveRelativeInfo(List<String> imagesList, Integer newId, Short type) {
        if (imagesList!=null&&!imagesList.isEmpty()){
            LambdaQueryWrapper<WmMaterial> wrapper=new LambdaQueryWrapper<>();
            wrapper.in(WmMaterial::getUrl,imagesList);
            List<WmMaterial> listWmMaterial = wmMaterialMapper.selectList(wrapper);

            if (listWmMaterial==null&&listWmMaterial.size()==0){
                throw new CustomException(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
            }

            if (imagesList.size()!=listWmMaterial.size()){
                throw new CustomException(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
            }

            List<Integer> idList = listWmMaterial.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //保存文章素材关系表
            wmNewsMaterialMapper.saveRelations(idList,newId,type);


        }
    }

    /**
     * 提取文章内容中的图片信息
     * @param content
     * @return
     */
    private List<String> imagesList(String content) {
        List<String> ImGs=new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")){
                String imgUrl = (String) map.get("value");
                ImGs.add(imgUrl);
            }
        }
        return ImGs;
    }
@Autowired
private WmNewsMapper wmNewsMapper;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Override
    public ResponseResult downorup(WmNewsDto wmNewsDto) {
//        LambdaQueryWrapper<WmNews> wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(WmNews::getId,wmNewsDtos.getId());
        WmNews wmNews = wmNewsMapper.selectById(wmNewsDto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        if (wmNews.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }

        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,
                    "当前文章不是发布状态,不能上架");
        }
        wmNews.setEnable(wmNewsDto.getEnable());

        wmNewsMapper.updateById(wmNews);

        if(wmNews.getArticleId()!=null){
            Map<String,Object> map=new HashMap<>();
            map.put("articleId",wmNews.getArticleId());
            map.put("enable",wmNews.getEnable());
        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    /**
     * 自媒体文章查询
     * @param dto
     * @return
     */
    public PageResponseResult ListVO(NewsAuthDto dto) {
        Page IPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper=new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(dto.getTitle()),WmNews::getTitle,dto.getTitle());
        if (dto.getStatus()!=null) {
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        wrapper.orderByDesc(WmNews::getCreatedTime);
        Page page = page(IPage, wrapper);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }
}